package com.vanguard.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.vanguard.commons.constant.CommonReturnCode;
import com.vanguard.commons.enums.StatusEnum;
import com.vanguard.commons.exception.BusinessException;
import com.vanguard.commons.utils.StringUtils;
import com.vanguard.domain.User;
import com.vanguard.mapper.UserMapper;
import com.vanguard.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * @Title:
 * @Description:
 * @Author: vanguard
 * @Version: 1.0
 * @Date: 2018/11/16
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Value("${appId}")
    private String appId;

    @Value("${appsecret}")
    private String appSecret;

    @Override
    public User getByOpenId(String openId) {
        User userParam = new User();
        userParam.setOpenId(openId);
        User user = userMapper.selectOne(userParam);
        return user;
    }

    @Override
    public String getOpenId(String code, String state) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId +"&secret=" + appSecret +"&code="+code+"&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = (String) jsonObject.get("openid");
        return openid;
    }

    @Override
    public void register(User user) {
        String idNumber = user.getIdNumber();
        //截取身份证号后六位
        user.setIdNumber(StringUtils.substring(idNumber, idNumber.length() -1 -6, idNumber.length() - 1));
        user.setCreateTime(new Date());
        user.setStatus(StatusEnum.NORMAL.getStatus());
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }
}
